#include "tffmpegsupporter.h"

TFFmpegSupporter::TFFmpegSupporter(QObject *parent) : QObject(parent)
{

}

Q_GLOBAL_STATIC(TFFmpegSupporter,ffmpegsupporter)
TFFmpegSupporter *TFFmpegSupporter::get()
{
    return ffmpegsupporter();
}

/*
 * 获取pts值
 * packet : 数据包
 * 返回值  : pts值
 */
int64_t TFFmpegSupporter::getPts(AVPacket *packet)
{
    int64_t pts = 0;
    if(packet->pts == AV_NOPTS_VALUE) {
        pts = packet->pts;
    }
    else {
        pts = packet->dts;
    }
    return pts;
}

/*
 * 延时时间值
 * ntimebase : 时间基准
 * packet    : 数据包
 * startTime : 起始时间
 * 返回值     : 延时时间
 */
qint64 TFFmpegSupporter::getDelayTime(AVRational ntimebase, AVPacket *packet, qint64 startTime)
{
    AVRational time_base_q = {1, AV_TIME_BASE};//AV_TIME_BASE_Q
    int64_t pts = getPts(packet);
    int64_t pts_time = av_rescale_q(pts, ntimebase, time_base_q);
    int64_t now_time = av_gettime() - startTime;
    int64_t offset_time = pts_time - now_time;
    return offset_time;
}

/*
 * 延时
 * ntimebase : 时间基准
 * packet    : 数据包
 * startTime : 起始时间
 */
void TFFmpegSupporter::delayTime(AVRational ntimebase, AVPacket *packet, qint64 startTime)
{
    qint64 offset_time = getDelayTime(ntimebase, packet, startTime);
    if ((offset_time > 0) && (offset_time < 1 * 1000 * 1000)) {
        av_usleep(offset_time);
    }
}

/*
 * 获取错误信息
 * nerrnum : 错误号
 */
QString TFFmpegSupporter::getError(int nerrnum)
{
    char errbuf[256] = { 0 };
    av_strerror(nerrnum, errbuf, sizeof(errbuf));
    return errbuf;
}

/*
 * 获取播放器参数
 * 返回值 : 播放器参数
 */
TFFCustomPlayer &TFFmpegSupporter::getFFCustomPlayer()
{
    return m_ffcustomPlayer;
}
